﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using QDP.Platform.Silverlight;
using QDP.Platform.Silverlight.Controls;
namespace Apps.Yunwei.Views
{
    public partial class PartSelector : ChildWindow
    {
        const string BASE_DIR = "clientbin";
        const string xap_is_null = "无";
        const string platform_xap_key = "无";
        const string platform_xap_value = "";

        private string xap = string.Empty;
        private string dll = string.Empty;
        private string cla = string.Empty;
        private string pe = string.Empty;
        private string xapUrl = string.Empty;

        public PartSelector()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(PartSelector_Loaded);
        }

        void PartSelector_Loaded(object sender, RoutedEventArgs e)
        {
            // 获取数据源初始数据
            dynamic bindData = this.DataContext;
            xap = bindData.URL;
            dll = bindData.Arg1;
            cla = bindData.Arg2;
            pe = bindData.Args;
            this.RequestXaps();
        }

        // 请求xap文件列表，并赋予cmbXap
        private void RequestXaps()
        {
            Q.ConfigManager.Request(Q.ConfigManager.GetUrl("catalog_xaps"), (s, ea) =>
            {
                if (s)
                {
                    var datas = (from data in ea.Split(';')
                                 select new KeyValuePair<string, string>(data, convert(data))).ToList();
                    datas.Insert(0, new KeyValuePair<string, string>(platform_xap_key, platform_xap_value));
                    cmbXap.ItemsSource = datas;
                    cmbXap.SelectedValue = xap;
                }
                else
                {
                    this.ShowMessage(ea);
                }
            });
        }
        // 请求xap文件中的dll列表，并赋予cmbAssembly
        private void GetDlls(string xapurl)
        {
            // 解析xap，列出dll清单；
            if (xapurl.Equals(platform_xap_key))
            {
                var source = new ObservableCollection<KeyValuePair<string, string>>();
                source.Add(new KeyValuePair<string, string>(platform_xap_key, platform_xap_value));

                cmbAssembly.ItemsSource = source;
                cmbAssembly.SelectedValue = platform_xap_value;

                Q.ConfigManager.Request(Q.ConfigManager.GetUrl("catalog_dlls"), (s, ea) =>
                {
                    if (s)
                    {
                        foreach (var data in ea.Split(';'))
                        {
                            source.Add(new KeyValuePair<string, string>(data, convert(data)));
                        }
                        cmbAssembly.SelectedValue = dll;
                    }
                    else
                    {
                        this.ShowMessage(ea);
                    }
                });
            }
            else
            {
                D.LoadXap(xapurl, (action) =>
                {
                    if (action.State == LoadActionState.Complated)
                    {
                        var sources = from i in D.GetAssemblies(xapurl)
                                      orderby i
                                      select new KeyValuePair<string, string>(i, i);
                        cmbAssembly.ItemsSource = sources;

                        if (string.IsNullOrEmpty(dll) == false && sources.Any(p => p.Key == dll))
                        {
                            cmbAssembly.SelectedValue = dll;
                        }
                        else
                        {
                            cmbAssembly.SelectedValue = null;
                        }
                    }
                });
            }
        }
        // 请求dll中的类别列表，并赋予cmbClass
        private void GetClasses(string dllname)
        {
            var data = (KeyValuePair<string, string>)cmbXap.SelectedItem;
            if (data.Key.Equals(platform_xap_key) && dllname.Equals(platform_xap_key) == false )
            {
                D.LoadDll(dllname, action =>
                {
                    if (action.State == LoadActionState.Complated)
                    {
                        this.FillClasses(xapUrl, dllname);
                    }
                });
            }
            else
            {
                this.FillClasses(xapUrl, dllname);
            }
        }
        private Assembly selectedAssembly = null;
        private void FillClasses(string package, string assembly)
        {
            if (package.Equals(platform_xap_key))
                package = string.Empty;
            if (assembly.Equals(platform_xap_key))
                assembly = string.Empty;
            selectedAssembly = D.GetAssembly(package, assembly);
            if (selectedAssembly != null)
            {
                var source = from i in selectedAssembly.GetTypes()
                             where (i.IsSubclassOf(typeof(UserControl)) || i.IsSubclassOf(typeof(PartElement)))
                             orderby i.FullName
                             select i.FullName;
                cmbClass.ItemsSource = source;
                if (string.IsNullOrEmpty(cla) == false && source.Any(p => p == cla))
                {
                    cmbClass.SelectedValue = cla;
                }
                else
                {
                    cmbClass.SelectedValue = null;
                }
            }
            else
            {
                cmbClass.ItemsSource = null;
                cmbClass.SelectedValue = null;
            }
        }
        // 请求类中的描述性内容
        private void GetClassMeta(string classname)
        {
            if (string.IsNullOrEmpty(classname)) return;

            var type = selectedAssembly.GetType(classname);
            var metas = new List<WidgetMetaAttribute>();
            if (type.IsSubclassOf(typeof(UserControl)))
            {
                metas = (from m in type.GetCustomAttributes(typeof(WidgetMetaAttribute), true)
                         select m as WidgetMetaAttribute).ToList();
                // 加载WidgetControl默认参数清单
                metas.AddRange((from m in typeof(WidgetControl).GetCustomAttributes(typeof(WidgetMetaAttribute), true)
                                select m as WidgetMetaAttribute).ToList());
                // 加载PartElement默认参数清单
                metas.AddRange((from m in typeof(PartElement).GetCustomAttributes(typeof(WidgetMetaAttribute), true)
                                select m as WidgetMetaAttribute).ToList());
            }
            else if (type.IsSubclassOf(typeof(PartElement)))
            {
                metas = (from m in type.GetCustomAttributes(typeof(WidgetMetaAttribute), true)
                         select m as WidgetMetaAttribute).ToList();
                // 加载PartElement默认参数清单
                metas.AddRange((from m in typeof(PartElement).GetCustomAttributes(typeof(WidgetMetaAttribute), true)
                                select m as WidgetMetaAttribute).ToList());
            }
            datagrid.SetSource(metas, this.DataContext);
        }
        private string convert(string text)
        {
            int index = text.ToLower().IndexOf(BASE_DIR);
            return text.Substring(index + BASE_DIR.Length + 1);
        }
        // 选中xap后列出dll清单
        private void Xap_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            object selected = cmbXap.SelectedItem;
            if (selected == null) return;
            var data = (KeyValuePair<string, string>)selected;
            GetDlls(xapUrl = data.Key);
        }
        // 选中dll后列出类型清单
        private void Assembly_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cmbAssembly.SelectedItem == null)
            {
                cmbClass.SelectedValue = null;
                return;
            }
            var data = (KeyValuePair<string, string>)cmbAssembly.SelectedItem;
            GetClasses(data.Key);
        }
        // 选中class后列出参数清单
        private void Class_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cmbClass.SelectedValue == null) return;
            GetClassMeta(cmbClass.SelectedValue.ToString());
        }
        // 取消操作
        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            dynamic bindData = this.DataContext;
            bindData.URL = xap;
            bindData.Arg1 = dll;
            bindData.Arg2 = cla;
            bindData.Args = pe;

            this.DialogResult = false;
        }
        // 确定操作
        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            dynamic bindData = this.DataContext;
            bindData.Args = datagrid.GetResult();

            string className = string.Empty;
            if (cmbClass.SelectedValue != null)
                className = cmbClass.SelectedValue.ToString();

            if (string.IsNullOrEmpty(bindData.Code))
                bindData.Code = className;
            if (string.IsNullOrEmpty(bindData.Caption))
                bindData.Caption = className;

            this.DialogResult = true;
        }
    }
}